package com.zodiac.app.szse.parse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Preconditions;
import lombok.Getter;

import java.io.File;

/**
 * PDF 转换为 HTML
 */
@Getter
public class Pdf2HtmlConverter {
    private File pdf;
    private File defaultHtml;
    private String log;
    private boolean htmlGenerated = false;

    public static Pdf2HtmlConverter create(File pdf) {
        Preconditions.checkNotNull(pdf);
        if (!pdf.exists() || !pdf.isFile()) {
            throw new RuntimeException("PDF文件不存在 -> " + pdf.getAbsolutePath());
        }
        final Pdf2HtmlConverter convert = new Pdf2HtmlConverter();
        convert.pdf = pdf;
        convert.defaultHtml = new File(pdf.getParentFile(), pdf.getName().substring(0, pdf.getName().lastIndexOf(".")) + ".html");
        return convert;
    }

    /**
     * 转换为默认的html文件
     *
     * @return
     */
    public Pdf2HtmlConverter convert() {
        return convert(this.defaultHtml);
    }

    /**
     * 转换为指定的html文件 space-as-offset 0
     *
     * @param html
     * @return
     */
    public Pdf2HtmlConverter convert(File html) {
        final String pdfPath = this.pdf.getAbsolutePath();
        final String htmlDestDir = html.getParentFile().getAbsolutePath();
        final String htmlName = html.getName();
        String command = "pdf2htmlEX --embed-css 0 --embed-font 0 --embed-image 0 --embed-javascript 0 --embed-outline 0 --dest-dir " + htmlDestDir + " " + pdfPath + " " + htmlName;
        final Cmd cmd = Cmd.create().exec(command);
        this.log = JSON.toJSONString(cmd, SerializerFeature.SortField);
        this.htmlGenerated = html.exists();
        return this;
    }
}
